<?php

namespace app\index\service;

use think\Db;
use \app\common\model\ToolModel;

/**
 * @author xjy
 */
class StoresalesService
{
    //SKU生命周期列表
    static public function getList($param)
    {
        if(empty($param['down'])){
             $titles=[];
        }else{
             $titles=[
                 'shop_name'=>'店铺','order_sn_sap'=>'SAP销售单号','sku'=>'SKU','order_time'=>'订单时间','seller'=>'销售人员','order_price'=>'销售单价','order_quantity'=>'销售数量','money'=>'销售金额',
                 'currency'=>'币种','exchange_rate'=>'汇率','rmbamount'=>'人民币金额','ship_warehouse'=>'发货仓','ship_time'=>'发货时间'];
        }
        
        return \app\index\model\StoresalesModel::getList($param,$titles,"app\index\service\StoresalesService::convertData");  
    }
    public static function convertData($data){
       
        $country=\app\common\ConfigBase::getCountry();
        $shop=\app\common\ConfigBase::getShopAll();
        if(!empty($data)){
            foreach($data as $key=>&$value){
                $value['country_name']=isset($country[$value['country']])? $country[$value['country']]:'';   
                $value['shop_name']=isset($shop[$value['shop']])? $shop[$value['shop']]:'';   
            }
        }
        return $data;  
    }
    /**
     * 更新sap销售订单（连接sqlserver）
     * @throws Exception
     * @author xiongjingyang
     */
    static public function getSapOrders()
    {
        ExchangeService::getExchangeByApi();
        $orderUpdate=[];$detail=[];$returnSapId=[];
        $push=[];
        $logParam = [
            "status" => 1,
            "method" => 'StoresalesService::getSapOrders',
            "response" => '',
            "sapIdArr"=>''
        ];
       try{
           $url="http://10.90.1.174:801/yujisopms/sap.php";
           $sapJson=curl($url,[], [],'GET');
           $sapOrder=json_decode($sapJson,true);
           $logParam['response']=$sapJson;
            if($sapOrder['code']!=1)
            {
                $logParam['status']=2;
                self::saveSapLog($logParam);
                returnJson('0',$sapJson);
            }else{
                if($sapOrder['data']){
                    ToolModel::startTrans();
                    $sku=array_column($sapOrder['data'],'sku');
                    $skuArr=\app\common\service\SkuService::getBatchInfoBySku($sku,['cnname']);
                    $shopInfo=self::getShopRelative();
                    foreach($sapOrder['data'] as $key=>$value){ 
                        $sap_code="sap_".$value['country']."_".$value['shopEntry'];
                        $sapInfo=isset($shopInfo[$sap_code]) ? $shopInfo[$sap_code] : [];
                       $one=[
                            "order_sn_sap"=>isset($value['orderid']) ? $value['orderid']:'',
                            "shop"=>isset($value['shopEntry'])? $value['shopEntry']:'',
                            "shop_name"=>isset($value['shopname']) ? $value['shopname']:'',
                            "country"=>isset($value['country']) ? $value['country']:'',
                            "seller"=>isset($value['empName']) ? $value['empName'] : '',  
                            "sap_code"=>$sap_code,
                            "order_time"=>isset($value['ordertime']['date']) ? date('Y-m-d H:i:s',strtotime($value['ordertime']['date'])) : '',
                            "ship_time"=>isset($value['ordertime']['date']) ? date('Y-m-d H:i:s',strtotime($value['ordertime']['date'])) : '',
                        ];
                       if($sapInfo){
                          foreach($sapInfo as $key=>&$val){
                             $val=(isset($sapInfo[$key]) && !empty($sapInfo[$key])) ? $sapInfo[$key] : '';
                          } 
                       }
                       $one=array_merge($one,$sapInfo);
                       unset($one['sap']);
                        $orderOne= ToolModel::findByAttributes('sap_order',['order_sn_sap'=>$value['orderid']],'id');
                        if(empty($orderOne)){ 
                            $id=ToolModel::insertData($one,'sap_order');
                        }else{
                            ToolModel::updateData(['order_sn_sap'=>$value['orderid']],$one,'sap_order');
                            $id=$orderOne['id'];
                        }
                        $push[]=$id;
                         $price=isset($value['price']) ? $value['price'] : 0;
                         $qty=isset($value['qty']) ? $value['qty'] : 0;
                         $exchange_rate=isset($sapInfo['exchange_rate'])?$sapInfo['exchange_rate']:0.00;
                         $rmbamount=bcdiv(bcmul($exchange_rate,$price*$qty,2),100,4);
                        $detail[]=[
                            "order_id"=>$id,
                            "order_price"=>$price,
                            "order_quantity"=>$qty,
                            "money"=>$price*$qty,
                            "rmbamount"=>$rmbamount,
                            "sku"=>$value['sku'],
                            "sku_name"=>isset($skuArr[$value['sku']]['cnname']) ? $skuArr[$value['sku']]['cnname']:'',
                            "from_orderid"=>isset($value['ID']) ? $value['ID']:0
                        ]; 
                        $orderUpdate[$id]['ids'][]=$price*$qty;
                        $orderUpdate[$id]['sap_code']=$sap_code;
                        $returnSapId[]=$value['ID'];
                    }
                       ToolModel::dbInsertOrUpdate('sap_order_detail',$detail);
                       if($orderUpdate){
                           foreach($orderUpdate as $key=>$value){
                               $money=array_sum($value['ids']);
                             //  $sapInfo=isset($shopInfo[$value['sap_code']]) ? $shopInfo[$value['sap_code']] : [];
                              // $rmbamount=bcdiv(bcmul($sapInfo['exchange_rate'],$money,2),100,4);
                               ToolModel::updateData(['id'=>$key],['money'=>$money],'sap_order');
                           }
                       }
                       $logParam['status']=1;
                       $logParam['sapIdArr']=json_encode($returnSapId);
                    }   
                }
           ToolModel::commit();
            //推送sap订单生成出库单(等正式上线的时候放开)
         //  self::pushShopWarehouseOut($push);
           self::saveSapLog($logParam);
           returnJson('1', '操作成功');
       }catch (Exception $e){
           trace($e->getMessage(), 'error');
           ToolModel::roolback();
           $logParam['status']=2;
           $logParam['response'].=";".$e->getMessage();
           self::saveSapLog($logParam);
           returnJson('0', '操作失败'.$e->getMessage());
       }
     } 
     //拉取sap订单的日志记录
    public static function saveSapLog($param=[]){
        $action = !empty($param['action']) ? $param['action'] : 'StoresalesService::getSapOrders';
        $status = !empty($param['status']) ? $param['status'] : 1;
        $request = !empty($param['request']) ? $param['request'] : '';  //json字符串
        $response = !empty($param['response']) ? $param['response'] : '';//json字符串
        $sapIdArr = !empty($param['sapIdArr']) ? $param['sapIdArr'] : '';//json字符串
        $operator =  CN_NAME ? CN_NAME : 'admin';
        $data_logs = array(
             "status" => $status,
             "method" => $action,
             "response" => $response,
             "request" => "operator = {$operator},params = {$request}",
             "return_sapId"=>$sapIdArr,
             "create_time" => date('Y-m-d H:i:s')
         );
         ToolModel::dbInsertOrUpdate('sap_logs',[$data_logs],['create_time']);
    }
    //获取yujiso相关的店铺的信息及其汇率信息
    public static function getShopRelative(){
      $exchange= \app\common\ConfigBase::getExchangeRateInfo();
      $field="a.id as shop,a.shop_name,a.base_country_id country,w.id ship_warehouse_id,w.warehouse_name ship_warehouse,a.currency_name currency";
      $result=Db::table('base_shop')->alias('a')
           ->join('base_warehouse w','a.id = w.base_shop_id','left')
            ->column($field,'sap');
      if($result){
          foreach($result as $key=>&$value){
              $value['exchange_rate']=isset($exchange[$value['currency']])? $exchange[$value['currency']]:'';
          } 
      }
      return $result;
    }
    //通过sap销售订单生成出库单
    public static function pushShopWarehouseOut($sapOrderArr=[]){
      if($sapOrderArr){
          foreach($sapOrderArr as $value){
              $where=['id'=>$value];
              $result=AllocateorderService::insertAllocateorderShopwarehouseoutData(['type'=>3,'id'=>$value]);
              $sapInfo=ToolModel::findByAttributes('sap_order',['id'=>$value]);
              
              if($result['code']!=1 && !empty($sapInfo)){
                  $condition=['status'=>2,'abnormalResult'=>$result['msg']];
              }else if($result['code']==1 && !empty($sapInfo)){
                  $condition=['status'=>1];
              }
              ToolModel::updateData($where,$condition,'sap_order');
          }
      }
      return true;
    }
    //重新推送失败sap订单
    public static function renewPushSapOrder(){
        $pushId=[];
        $sap_order_ids =ToolModel::select('shop_stock_logs',['type'=>3,'status'=>0],'request');
        if($sap_order_ids){
            foreach($sap_order_ids as $value){
                $id=json_decode($value,true);
                $pushId[]=$id['sap_order_id'];
            }
        }
        self::pushShopWarehouseOut($pushId);
    }
    //批量更新异常订单
     public static function batchUpdateAbsolute(){
        $pushId = ToolModel::select('sap_order',['status'=>2],'id','','id');
        self::pushShopWarehouseOut($pushId);
    }
}
